﻿#include "icon_helper.h"
#include <QMutex>
#include <QFontDatabase>
#include <QPainter>

static const QMap<IconHelper::EFonts, QString> fontPathMap = {
    {IconHelper::EFonts::FontAwesome6Light, ":/fa-light-300.ttf"},
    {IconHelper::EFonts::FontAwesome6Regular, ":/fa-regular-400.ttf"},
    {IconHelper::EFonts::FontAwesome6Solid, ":/fa-solid-900.ttf"},
    {IconHelper::EFonts::FontAwesome6Brands, ":/fa-brands-400.ttf"},
    {IconHelper::EFonts::FontAwesome6Duotone, ":/fa-duotone-900.ttf"}
};

IconHelper::IconHelper(QObject* parent) : QObject{parent}
{
    QFontDatabase fontDb;
    int fontId;

    QMapIterator<IconHelper::EFonts, QString> i(fontPathMap);
    while (i.hasNext()) {
        i.next();
        IconHelper::EFonts key = i.key();
        QString value = i.value();

        fontId = fontDb.addApplicationFont(value);
        if(-1 == fontId)
            return;

        QStringList fontFamilies = fontDb.applicationFontFamilies(fontId);
        if ( fontFamilies.count() > 0 ) {
            QFont* font = new QFont(fontFamilies.at(0));
            font->setHintingPreference(QFont::PreferNoHinting);
            m_fonts.insert(key, font);
        }
    }
}

IconHelper* IconHelper::self = nullptr;
IconHelper* IconHelper::instance() {
    if ( !self ) {
        /*
         * 这里定义局部变量，简化锁定和解锁的操作
         * */
        QMutex mutex;
        QMutexLocker locker(&mutex);
        if ( !self ) {
            self = new IconHelper();
        }
    }

    return self;
}

bool IconHelper::setIcon(QLabel* lbl, EFonts fontFamily, int icon, quint8 size) {
    if(!m_fonts.contains(fontFamily))
        return false;

    QFont* font = m_fonts.value(fontFamily);
    font->setPixelSize(size);
    lbl->setFont(*font);
    lbl->setText((QChar)icon);
    return true;
}

bool IconHelper::setIcon(QAbstractButton* btn, EFonts fontFamily, int icon, quint8 size)
{
    if(!m_fonts.contains(fontFamily))
        return false;

    QFont* font = m_fonts.value(fontFamily);
    font->setPixelSize(size);
    btn->setFont(*font);
    btn->setText((QChar)icon);
    return true;
}

QPixmap IconHelper::getPixmap(const QColor& color, EFonts fontFamiliy, int icon, quint8 size, quint8 width, quint8 height)
{
    if(!m_fonts.contains(fontFamiliy))
        return QPixmap();

    QFont* font = m_fonts.value(fontFamiliy);

    // 把图标字体绘制到图片上
    QPixmap pix(width, height);
    pix.fill(Qt::transparent);

    QPainter painter;
    painter.begin(&pix);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
    painter.setPen(color);

    font->setPixelSize(size);
    painter.setFont(*font);

    painter.drawText(pix.rect(), Qt::AlignCenter, (QChar)icon);
    painter.end();

    return pix;
}
